<template>
<div class="contain">
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <header-box :title="'加班申请'" :hasArrow="true"></header-box>
  <detail-user></detail-user>
  <progress-box :formData="true" @showLoadProgress="showLoadProgress"></progress-box>
  <div class="form-control displayflex">
    <div class="label require">开始时间</div>
    <div class="ctx-wrap flex1">
      <datetime v-model="applydate" 
          format="YYYY-MM-DD HH:mm:00"
          year-row="{value}年" month-row="{value}月" day-row="{value}日" hour-row="{value}时" minute-row="{value}分">{{applydate}}</datetime>
      <div v-if="!applydate" class="remind">请选择</div>
    </div>
    <i class="iconfont icon-arrow"></i>
  </div>
  <div class="form-control displayflex">
    <div class="label require">结束时间</div>
    <div class="ctx-wrap flex1">
      <datetime v-model="endtime" 
          format="YYYY-MM-DD HH:mm:00"
          year-row="{value}年" month-row="{value}月" day-row="{value}日" hour-row="{value}时" minute-row="{value}分">{{endtime}}</datetime>
      <div v-if="!endtime" class="remind">请选择</div>
    </div>
    <i class="iconfont icon-arrow"></i>
  </div>
  <div class="form-control displayflex">
    <div class="label require">加班时长</div>
    <div class="ipt-wrap flex1"><input type="number" v-model="overtimedays"/></div>
    <div class="unit">天</div>
  </div>
  <div class="form-control displayflex">
    <div class="label require">加班事由</div>
    <!-- <div class="ipt-wrap flex1"><input type="text" style="ime-mode:active;" placeholder="请填写加班事由" v-model="reasons"/></div> -->
    <div class="text-wrap flex1">
      <textarea rows="3" placeholder="请填写加班事由" v-model="reasons"></textarea>
    </div>
  </div>
  <uploader-img :attaches="attaches" @getImgArr="getImgArr" ref="uploader"></uploader-img>
  
  <div class="btn-group displayflex">
    <div class="flex1 save" @click="changeImg(1)">保 存</div>
    <div class="flex1 submit" v-if="btnGroup.wfsubmit || !guid" @click="changeImg(2)">提 交</div>
    <div class="dele" v-if="guid" @click="deleForm"><i class="iconfont icon-delbtn"></i></div>
  </div>
</div>
</template>
<script>
import detailUser from "@/components/share/detailUser.vue";
import uploaderImg from "@/components/share/uploaderImg.vue";
import progressBox from "@/components/share/progress.vue";
import axios from "axios";

export default {
  components:{
    detailUser,
    uploaderImg,
    progressBox
  },
  data() {
    return {
      overtimedays:'',
      applydate:'',
      endtime:'',
      reasons:'',
      btnGroup:'',
      showLoad:false,
      showLoadT:false,
      showLoadP:false,

      savedGuid:'',
      attaches:[],
      fileattaches:[],
      attachesBase:[],
    }
  },
  watch:{
    showLoadT(newVal, oldVal){
      if(this.showLoadT == false && this.showLoadP == false){
        this.showLoad = false;
      } else {
        this.showLoad = true;
      }
    },
    showLoadP(newVal, oldVal){
      if(this.showLoadT == false && this.showLoadP == false){
        this.showLoad = false;
      } else {
        this.showLoad = true;
      }
    },
  },
  computed: {
    userInfo(){
      return localStorage.UserInfo?JSON.parse(localStorage.UserInfo):'';
    },
    guid(){
      return this.$route.query.guid || "";
    },
    bizdataguid(){
      return this.$route.query.bizdataguid || "";
    },
  },
  created() {
    if(this.guid){
      this.getBtn();
      this.getData();
    }
  },
  methods:{

    //获取上传的图片
    getImgArr(val){
      // console.log(val,"选择的图片base6")
      this.attachesBase = val;
    },

    //获取详情页
    getData(){
      var data = {
            "guid": this.bizdataguid || this.guid
          };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('OvertimeService/GetOvertimeApplyById',data).then(function(resp) {
        _this.showLoadT = false;
        if(resp.code == 'SUCC'){
          var detailCtx = JSON.parse(resp.data);
          // console.log(detailCtx,"加班明细")
          _this.overtimedays = detailCtx.overtimedays;
          _this.applydate= detailCtx.applydate.replace("T", " ");
          _this.endtime = detailCtx.enddate.replace("T", " ");
          _this.reasons = detailCtx.reasons;
          if(detailCtx.attaches && detailCtx.attaches != ''){
            var attachesArr = JSON.parse(detailCtx.attaches);
            var formatArr = ['gif','jpeg','jpg','png'];
            var picArr = [];
            for(let i in attachesArr){
              var url = attachesArr[i].url
              var format = url.split('.')[1];
              if(formatArr.indexOf(format)>-1){
                _this.attaches.push(attachesArr[i])
              }else{
                _this.fileattaches.push(attachesArr[i]);
              }
            }
          }
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
      });
    },

    //判断按钮权限（提交 撤回 审核）
    getBtn(){
      var data = {
                "bizguid": this.guid,
                "pagekey": "MyOvertimeApply",// 可用场景MyOvertimeApply   OvertimeApplyAudit
                "staffid": this.userInfo.staffid,
                "todoguid": ""
            };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('OvertimeService/WFAvailableButtons',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          // console.log(JSON.parse(resp.data),"%%")
          _this.btnGroup = resp.data?JSON.parse(resp.data):'';
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        }
        _this.showLoadT = false;
      });
    },

    //删除
    deleForm(){
      var data = {
                "guid": this.guid
            };
      var _this = this;
      this.$vux.confirm.show({
        title:'提示',
        content: '确认删除申请吗？',
        onConfirm () {
          _this.showLoadT = true;
          _this.Ajax.post('OvertimeService/MyOvertimeApplyDelete',data).then(function(resp) {
            if(resp.code == 'SUCC'){
              _this.$vux.toast.show({
                type: "success", //success, warn, cancel, text
                text: resp.message,
                onHide () {
                  // _this.$router.push({
                  //   path:'/workOvertime/list'
                  // })
                  _this.$router.go(-1);
                }
              });
            }else{
              _this.$vux.toast.show({
                type: "warn", //success, warn, cancel, text
                text: resp.message
              });
            }
            _this.showLoadT = false;
          });
        }
      });
    },

    //表单验证
    checkForm(){
      if(!this.applydate){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "加班日期不能为空"
        });
        return false;
      };
      if(!this.overtimedays){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "加班时长不能为空"
        });
        return false;
      };
      if(!this.reasons){
        this.$vux.toast.show({
          type: "warn", //success, warn, cancel, text
          text: "加班事由不能为空"
        });
        return false;
      };
      return true;
    },

    //转换图片
    changeImg(step){
      const uploadApi = process.env.API_ROOT + '/app/openroute/CSBR.Management.AppService.Service.V1.DataService/FilesUpload';
      this.showLoadT = true;
      var attachesBase = this.attachesBase;
      var data = [];
      var _this = this;
      if(attachesBase.length == 0){
        this.save(step);
        return false;
      }
      for(let i in attachesBase){
        //接口调整图片前缀
        // let pic = attachesBase[i].indexOf('base64,') > -1?attachesBase[i].split('base64,')[1]:attachesBase[i];
        let pic = attachesBase[i].replace(/\n/g, '');

        let timestamp =new Date().getTime(),
            item = {
              "base64code" : pic,
            };
        data.push(item);
      };

      //new batch upload
      let reqList = [],
          resList = [],
          picNewArr = [],
          hasError = false;
      for(let i = 0; i < data.length; i++)
      {
        let item = [data[i]];
        let req = axios.post(uploadApi,item)
        reqList.push(req);
      }

      axios.all(reqList)
        .then(axios.spread(function(...resList) {
          resList.forEach((item) => {
            if(item.data.code == 'SUCC')
            {
              let url = JSON.parse(item.data.data)[0],
                  filename = url.split('/')[2],
                  result = {
                    type : null,
                    url : url,
                    fileid: null,
                    filename: filename
                  };
              picNewArr.push(result);
            }
            else
            {
              hasError = true;
            }
          });
          
          _this.attachesBase = [];
          _this.$refs.uploader.resetImgListBase();

          if(_this.attaches){
            _this.attaches = _this.attaches.concat(picNewArr);
          } else {
            _this.attaches = picNewArr;
          };

          if(hasError) {
            _this.showLoadT = false;
            _this.$vux.toast.show({
              type: "warn", //success, warn, cancel, text
              text: "部分图片上传发生错误，请重试"
            });
          } else {
            // console.log(_this.attaches);
            _this.save(step);
          }
        })
      );
      //new batch upload

      // this.Ajax.post('DataService/FilesUpload',data).then(function(resp) {
      //   if(resp.code == 'SUCC'){
      //     var picData = JSON.parse(resp.data);
      //     var picNewArr = [];
      //     for(let j in picData){
      //       let filename = picData[j].split('/')[2];
      //       var result = {
      //         type : null,
      //         url : picData[j],
      //         fileid: null,
      //         filename: filename
      //       };
      //       picNewArr.push(result);

      //       _this.attachesBase = [];
      //       _this.$refs.uploader.resetImgListBase();
      //     };
      //     if(_this.attaches){
      //       _this.attaches = _this.attaches.concat(picNewArr);
      //     } else {
      //       _this.attaches = picNewArr;
      //     };
      //     _this.save(step);
      //   }else{
      //     _this.showLoadT = false;
      //     _this.$vux.toast.show({
      //       type: "warn", //success, warn, cancel, text
      //       text: resp.message
      //     });
      //   }
      // });
    },

    //保存
    save(step){
      if(!this.checkForm()){
        this.showLoadT = false;
        return false;
      };

      var _this = this;
      this.showLoadT = true;
      
      //attaches定义附件合并，需要包含this.attaches和this.fileattaches;
      let mixedAttaches = [];
      if(this.attaches.length > 0)
      {
        mixedAttaches = mixedAttaches.concat(this.attaches);
      }
      if(this.fileattaches.length > 0)
      {
        mixedAttaches = mixedAttaches.concat(this.fileattaches)
      }

      var data = {
          "guid": this.guid,     // 空则为新增，非空则为编辑
          "applicant": this.userInfo.name,
          "staffid": this.userInfo.staffid,
          "deptguid": this.userInfo.deptguid,
          "deptname": this.userInfo.deptname,
          "applydate": this.applydate,
          "enddate": this.endtime,
          "overtimedays": this.overtimedays,
          "reasons": this.reasons,
          "attaches": mixedAttaches.length > 0 ? JSON.stringify(mixedAttaches):'',
      };

      if(this.savedGuid != '')
      {
        data.guid = this.savedGuid;
      }
      this.Ajax.post('OvertimeService/MyOvertimeApplySave',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          var guid = (JSON.parse(resp.data)).guid;
          _this.savedGuid = guid;
          if(step=="2"){
            _this.submit(guid);
          }else{
            _this.$vux.toast.show({
              type: "success", //success, warn, cancel, text
              text: resp.message
            });
            _this.showLoadT = false;
          }
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
          _this.showLoadT = false;
        };
      });
    },
    
    //提交
    submit(id){
      var data = { 
          "bizguid": id,///保存生成的guid,,,,
          "pagekey": "MyOvertimeApply", // 可用场景 MyBizTripApply    BizTripAudit
          "staffid": this.userInfo.staffid,
          "todoguid": "",
          "result": "Y",
          "rejectreason": ""
      };
      var _this = this;
      _this.showLoadT = true;
      this.Ajax.post('OvertimeService/Submit',data).then(function(resp) {
        if(resp.code == 'SUCC'){
          _this.$vux.toast.show({
            type: "success", //success, warn, cancel, text
            text: "提交成功",
            onHide () {
              _this.$router.go(-1);
            }
          });
        }else{
          _this.$vux.toast.show({
            type: "warn", //success, warn, cancel, text
            text: resp.message
          });
        };
        _this.showLoadT = false;
      });
    },

    showLoadProgress(val){
      this.showLoadP = val;
    }

  }
}
</script>